package com.example.maastock.ontime.quartz;

import lombok.extern.slf4j.Slf4j;
import org.quartz.Job;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.impl.StdSchedulerFactory;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
@Order(value = 2)
@Slf4j
public class InitTaskJobConfig implements CommandLineRunner {
    @Autowired
    TaskJobMapper taskJobMapper;




    @Override
    public void run(String... strings) throws Exception {

        //读取所有任务
//        List<TaskJobBean> list = taskJobMapper.findAllTaskJob();
        List<TaskJobBean> list = new ArrayList<>();
        //创建调度容器
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        list.stream().forEach(taskJobBean -> {
            try {
                System.out.println(taskJobBean.toString());
                //创建具体的可执行的调度程序
                //设置调度参数
                CronTriggerImpl cronTrigger = new CronTriggerImpl();
                cronTrigger.setName(taskJobBean.getJobName());
                cronTrigger.setCronExpression(taskJobBean.getJobCron());
                JobDetail jobDetail = JobBuilder.newJob((Class<? extends Job>) Class.forName(taskJobBean.getJobClassName())).build();

                //加入调度容器
                scheduler.scheduleJob(jobDetail, cronTrigger);
                //启动
                scheduler.start();
            } catch (Exception e) {
                log.error("job 启动异常",e);
            }
        });
    }
}
